﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Plat.WfProcess.Common;
using Plat.WfProcess.Business;
using Plat.WfProcess.DataModel;
using Plat.WfProcess.Utility;

namespace Plat.WfProcess.Engine
{
    internal class NodeMediatorStart : NodeMediator
    {
        internal NodeMediatorStart(ActivityExecutionContext activityExecutionObject)
            : base(activityExecutionObject)
        {

        }

        /// <summary>
        /// 执行开始节点
        /// </summary>
        /// <param name="activityExecutionObject"></param>
        /// <param name="processInstance"></param>
        internal override void ExecuteWorkItem()
        {
            WfLinqDataContext.Transaction = DataBaseHelper.BeginTransaction(WfLinqDataContext);
            try
            {
                //写入流程实例
                ProcessInstanceManager pim = new ProcessInstanceManager(ActivityExecutionContext.ProcessInstance.ProcessInstanceGUID);
                pim.Insert(ActivityExecutionContext.ProcessInstance,
                    WfLinqDataContext);

                //自动完成开始节点(开始节点不参与Task)
                NodeBase startNode = CreateNewNode(ActivityExecutionContext.Activity);
                ICompleteAutomaticlly autoStartNode = (ICompleteAutomaticlly)startNode;
                autoStartNode.CompleteAutomaticlly(ActivityExecutionContext.ProcessInstance,
                    null,
                    null,
                    ActivityExecutionContext.ActivityResource,
                    WfLinqDataContext);

                //执行开始节点之后的节点集合
                bool isContinuingSucceed = ContinueForwardCurrentNode(startNode,
                   ActivityExecutionContext.ActivityResource);

                if (isContinuingSucceed)
                {
                    WfLinqDataContext.Transaction.Commit();
                }
                else
                {
                    WfLinqDataContext.Transaction.Rollback();
                }
            }
            catch (System.Exception ex)
            {
                WfLinqDataContext.Transaction.Rollback();
                throw;
            }
        }

        internal override NodeBase CreateNewNode(ActivityEntity activity)
        {
            return new StartNode(activity);
        }
    }
}
